import axios from 'axios';
import TokenStorage from "../utils/token.js";
import router from "../router/index.js";
import {ElMessage} from "element-plus";
const api = axios.create({
    baseURL: '/api',
});
const gotoLogin = () => {
    router.push({path:'/login'})
}
api.interceptors.request.use(
    config => {
        const token = TokenStorage.getToken();  // 从本地存储中获取令牌
        console.log("获取到的token============>"+token)
        if (token) {
            // 在请求头中添加令牌
            config.headers['token'] = token;
        }
        console.log(config);
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

api.interceptors.response.use(
    response => {
        console.log(response);
        console.log("拦截器拦截数据 "+response);
        console.log(response.status);
        if (response.data.msg==='令牌已过期') {  // 令牌过期或无效的状态码
            console.log('111')
            // 移除令牌
            TokenStorage.remove();
            ElMessage({
                message: '授权信息过期请重新登录',
                duration: 1500, // 设置显示时间为 1.5 秒
            });
            // 跳转到登录页面
            gotoLogin();
        }
        return response;
    },
    error => {
        console.log(error);
    }
);
export default api
